<template>
  <div class="role-container">
    <div class="rc-1">
      <el-button v-permission="'add-role'" type="primary" size="medium" @click.prevent="openDialogTmp">添加角色</el-button>
    </div>
    <div class="rc-2">
      <el-table
        :data="roleList"
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="name"
          label="角色"
          width="180"
        >
          <template v-slot="{row}">
            <div v-if="row.isEdit">
              <el-input v-model="editform.name" />
            </div>
            <div v-else>{{ row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="state"
          label="启用"
        >
          <template slot-scope="{ row }">
            <div v-if="row.isEdit">
              <el-switch
                v-model="addform.state"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
              />
            </div>
            <div v-else @click="test(row)">{{ row.state == 1 ? '已启用' : '未启用' }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          width="800"
        >
          <template v-slot="{row}">
            <div v-if="row.isEdit">
              <el-input v-model="editform.description" />
            </div>
            <div v-else>{{ row.description }}</div>
          </template></el-table-column>
        <el-table-column label="操作" fixed="right" width="180">
          <template slot-scope="{ row }">
            <template v-if="row.isEdit">
              <el-button size="primary" type="text" @click="editSubmitTmp(row)">确 定</el-button>
              <el-button size="small" type="text" @click="row.isEdit =false">取 消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="small" @click="assignPermisionTmp(row.id)">分配权限</el-button>
              <el-button type="text" size="small" @click="editRowTmp(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="confirm(row.id)"
              >
                <el-button slot="reference" type="text" size="small">删除</el-button>
              </el-popconfirm>
              <!-- <el-button type="text" size="small" @click="delRoleTmp(row.id)">删除</el-button> -->
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="rc-3">
      <el-pagination
        :total="total"
        :current-page.sync="form.page"
        :page-size="form.pagesize"
        layout=" prev, pager, next,total"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog title="新增角色" :visible.sync="dialogFormVisible" :append-to-body="true">
      <el-form ref="ruleForm" :model="addform" :rules="rules">
        <el-form-item label="角色名称" :label-width="'150px'" prop="name">
          <el-input v-model="addform.name" />
        </el-form-item>
        <el-form-item label="启用" :label-width="'150px'" prop="state">
          <el-switch
            v-model="addform.state"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
          /></el-form-item>

        <el-form-item label="角色描述" :label-width="'150px'" prop="description">
          <el-input v-model="addform.description" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-if="dialogVisible"
      title="分配权限"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-tree ref="tree" :data="treeList" node-key="id" show-checkbox default-expand-all :props="{label: 'name', children: 'children'}" />
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="assingPermissionSubmitTmp">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addRoleListRequest, getRoleListRequest, deleteRoleRequest, updataRoleRequest, getRoleDetailRequest, assignPremRequest } from '@/api/role'
import { getPermissionRequest } from '@/api/permission'
import { transformListToTree } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      dialogFormVisible: false,
      roleList: [],
      form: {
        page: 1,
        pagesize: 5
      },
      total: 0,
      addform: {
        name: '',
        description: '',
        state: 1
      },
      editform: {
        name: '',
        description: '',
        state: 1
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      treeList: [],
      currentRoleId: null
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await getRoleListRequest(this.form)
      console.log(res.data.rows)
      this.roleList = res.data.rows
      this.total = res.data.total
      this.roleList.forEach(item => {
        this.$set(item, 'isEdit', false)
      })
    },
    handleCurrentChange(val) {
      this.form.page = val
      this.getRoleList()
    },
    openDialogTmp() {
      try {
        this.dialogFormVisible = true
      } catch (error) {
        //
      }
    },
    close() {
      this.dialogFormVisible = false
      this.$refs.ruleForm.resetFields()
    },
    submitForm() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          try {
            await addRoleListRequest(this.addform)
            this.close()
            this.$message.success({ message: '新增成功' })
            this.getRoleList()// 刷新
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    async confirm(id) {
      console.log(id)
      try {
        await deleteRoleRequest(id)
        this.$message.success({
          type: 'success',
          message: '删除成功' })
        if (this.roleList.length === 1) {
          if (this.form.page > 1) {
            this.form.page--
          }
        }
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    editRowTmp(row) {
      this.roleList.forEach(item => {
        item.isEdit = false
      })
      row.isEdit = true
      console.log(row.isEdit)
      this.editform = { ...row }
    },
    async editSubmitTmp(row) {
      try {
        await updataRoleRequest(this.editform)
        this.$message.success({ message: '修改成功' })
        this.getRoleList()// 刷新
      } catch (error) {
        console.log(error)
      }
    },
    assignPermisionTmp(id) {
      this.currentRoleId = id
      this.getPermissionList()
      this.dialogVisible = true
    },
    async getPermissionList() {
      const res = await getPermissionRequest()
      this.treeList = transformListToTree(res.data, 0)
      const res1 = await getRoleDetailRequest(this.currentRoleId)
      this.$refs.tree.setCheckedKeys(res1.data.permIds)
    },
    async assingPermissionSubmitTmp() {
      this.dialogVisible = false
      // 获取到用户勾选了那几个key
      console.log(this.$refs.tree.getCheckedKeys())
      this.$refs.treeList.resetFields()
      await assignPremRequest({
        id: this.currentRoleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success({ message: '分配成功' })
      this.getRoleList
    }
  }
}
</script>

<style lang="scss" scoped>
.role-container{
  margin: 30px 50px;
  .rc-2{
    margin: 20px 0;
  }
  .rc-3{
    text-align: center;
  }
}
</style>
